package com.newshub.ai.controller;

import com.newshub.ai.model.dto.ChatRequest;
import com.newshub.ai.model.dto.ChatResponse;
import com.newshub.ai.service.ChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;

/**
 * 聊天控制器
 * 提供聊天相关的API接口
 */
@Slf4j
@RestController
@RequestMapping("/api/ai/chat")
@CrossOrigin(origins = "*")
public class ChatController {

    @Autowired
    private ChatService chatService;



        /**
     * 发送聊天消息（流式）
     */
     @PostMapping(value = "/send-stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
     @CrossOrigin(origins = "*", allowedHeaders = "*", methods = {RequestMethod.POST})
     public SseEmitter sendMessageStream(@RequestBody ChatRequest request) {
         log.info("收到流式聊天请求: {}", request.getMessage());
         
         try {
             return chatService.processStreamChat(request);
         } catch (Exception e) {
             log.error("流式聊天接口异常", e);
             // 创建错误响应
             SseEmitter errorEmitter = new SseEmitter();
             try {
                 errorEmitter.send(SseEmitter.event()
                     .name("error")
                     .data("聊天服务异常: " + e.getMessage()));
                 errorEmitter.complete();
             } catch (IOException ex) {
                 log.error("发送错误事件失败", ex);
                 errorEmitter.completeWithError(ex);
             }
             return errorEmitter;
         }
     }

     /**
      * 发送聊天消息（同步）
      */
     @PostMapping("/send")
     public ResponseEntity<ChatResponse> sendMessage(@RequestBody ChatRequest request) {
        log.info("收到同步聊天请求: {}", request.getMessage());
        
        try {
            ChatResponse response = chatService.sendMessage(request);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("同步聊天接口异常", e);
            ChatResponse errorResponse = ChatResponse.error("聊天服务异常: " + e.getMessage());
            return ResponseEntity.internalServerError().body(errorResponse);
        }
    }





    /**
     * 获取服务状态
     */
    @GetMapping("/status")
    public ResponseEntity<String> getServiceStatus() {
        log.info("获取聊天服务状态");
        
        try {
            String status = chatService.getServiceStatus();
            return ResponseEntity.ok(status);
        } catch (Exception e) {
            log.error("获取服务状态异常", e);
            return ResponseEntity.internalServerError().body("服务状态异常: " + e.getMessage());
        }
    }

    /**
     * 健康检查
     */
    @GetMapping("/health")
    public ResponseEntity<String> health() {
        return ResponseEntity.ok("AI聊天服务运行正常");
    }
}
